package GUILayer;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;


import ControlLayer.DiscountCtr;

import ModelLayer.Discount;

public class DiscountGUI extends JPanel{
	private static final long serialVersionUID = 1L;
	private DiscountCtr discountCtr;
	private DefaultTableModel discountTableModel;
	private JScrollPane discountTableScrollPane;
	private JPanel showAllDiscountPanel;
	private JTable showAllDiscountTable;
	private JPanel discountInfoPanel;
	private JPanel choicePanel;


	private JTextField textField_searchId;
	private JTextField textField_discountPercent;
	private JTextField textField_minPrice;
	
	private JTextField textField_discountId;

	private JButton btnSave;
	private JButton btnCreate;
	private JButton btnEdit;
	private JButton btnCancel;
	private JButton btnDelete;



	public DiscountGUI() {
		discountCtr = new DiscountCtr();
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());

		showAllDiscountPanel = new JPanel();
		this.add(showAllDiscountPanel, BorderLayout.CENTER);
		showAllDiscountPanel.setBorder(BorderFactory
				.createTitledBorder("Discounts Info"));
		showAllDiscountPanel.setLayout(new BorderLayout());

		textField_searchId = new JTextField();
		textField_searchId.setColumns(10);
		JButton btnSearch = new JButton("Search");
		
		JLabel lblId = new JLabel("Id: ");

		JPanel searchPanel = new JPanel();
		searchPanel.setLayout(new FlowLayout());
		searchPanel.add(lblId);
		searchPanel.add(textField_searchId);
		searchPanel.add(btnSearch);
		showAllDiscountPanel.add(searchPanel, BorderLayout.NORTH);

		// show customer info view
		JPanel showDiscountPanel = new JPanel();
		this.add(showDiscountPanel, BorderLayout.EAST);
		showDiscountPanel.setLayout(new BorderLayout());
		showDiscountPanel.setBorder(BorderFactory
				.createTitledBorder("Discount"));

		discountInfoPanel = new JPanel();
		JLabel lbldiscountPercent = new JLabel("Discount Percent: ");
		JLabel lblminPrice = new JLabel("minPrice: ");
		JLabel lblDiscountId = new JLabel("Discount Id: ");
		
		textField_discountId = 	new JTextField();
		textField_discountId.setEditable(false); // Id is not able changed
		textField_discountPercent = new JTextField();
		textField_minPrice = new JTextField();



	
		GroupLayout gl = new GroupLayout(discountInfoPanel);
		discountInfoPanel.setLayout(gl);
		discountInfoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblDiscountId)
								.addComponent(lbldiscountPercent)
								.addComponent(lblminPrice)
								)
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_discountId)
								.addComponent(textField_discountPercent)
								.addComponent(textField_minPrice)
								));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblDiscountId)
								.addComponent(textField_discountId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbldiscountPercent)
								.addComponent(textField_discountPercent))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblminPrice)
								.addComponent(textField_minPrice))
				);

		showDiscountPanel.add(discountInfoPanel, BorderLayout.NORTH);

		choicePanel = new JPanel();
		choicePanel.setLayout(new FlowLayout());
		btnCreate = new JButton("Create");
		btnEdit = new JButton("Edit");
		btnDelete = new JButton("Delete");
		btnSave = new JButton("Save");
		btnCancel = new JButton("Cancel/Clear");

		choicePanel.add(btnCreate);
		choicePanel.add(btnEdit);
		choicePanel.add(btnSave);
		choicePanel.add(btnDelete);
		choicePanel.add(btnCancel);
		showDiscountPanel.add(choicePanel, BorderLayout.CENTER);
		setBtnStartStatue();

		addDiscountsTable();
		showAllDiscounts();

		// button function
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (showDiscount(getTextFieldId(textField_searchId))) {
					textField_searchId.setText("");
					setBtnEditStatue();
					isTextFieldEditable(false);
				}
			}
		});

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {discountCtr.insertDiscount(Double.parseDouble(textField_discountPercent.getText()),
						Integer.parseInt(textField_minPrice.getText()));
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				cleanTextField();
				showAllDiscounts();
			}
		});
		// TODO
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int reply = JOptionPane.showConfirmDialog(null,
						"Do you want to delete this discount ?",
						"Delete Discount", JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);
				if (reply == JOptionPane.YES_OPTION) {
					try {
						discountCtr.deleteDiscount(Integer
								.parseInt(textField_discountId.getText()));
						cleanTextField();
						setBtnStartStatue();
						showAllDiscounts();
					} catch (Exception e1) {
					}
				}
			}
		});

		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isTextFieldEditable(true);
				btnSave.setEnabled(true);
				btnDelete.setEnabled(true);
				btnCreate.setEnabled(false);
			}
		});

		btnSave.addActionListener(new ActionListener() {
		

			public void actionPerformed(ActionEvent e) {
				try {
				discountCtr.updateDiscount(
						Integer.parseInt(textField_discountId.getText()),
						Double.parseDouble(textField_discountPercent.getText()),
						Integer.parseInt(textField_minPrice.getText()));
				} catch (Exception a) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
				setBtnStartStatue();
				showAllDiscounts();
			}
		});

		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
				isTextFieldEditable(true);
				setBtnStartStatue();
			}
		});

	}

	public void addDiscountsTable() {
		discountTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		discountTableModel.addColumn("ID");
		discountTableModel.addColumn("DiscountPercent");
		discountTableModel.addColumn("MinRequirePrice");
		
		discountTableScrollPane = new JScrollPane();

		showAllDiscountPanel.add(discountTableScrollPane, BorderLayout.CENTER);

		showAllDiscountTable = new JTable(discountTableModel);
		showAllDiscountTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllDiscountTable.setAutoCreateRowSorter(true);

		showAllDiscountTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				btnCreate.setEnabled(false);
				btnEdit.setEnabled(true);
				int row = showAllDiscountTable.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 2) {
					if (showDiscount(Integer
							.valueOf((Integer) showAllDiscountTable.getValueAt(
									row, 0)))) {
					}
				}
			}
		});
		discountTableScrollPane.setViewportView(showAllDiscountTable);
	}

	public void showAllDiscounts() {
		ArrayList<Discount> discounts = discountCtr.getAllDiscount();
		discountTableModel.setRowCount(0);
		for (Discount discount : discounts) {
			try {
				discountTableModel.addRow(new Object[] { discount.getDiscountId(),
				discount.getDiscountPercentage(), discount.getMinPriceRequired() });
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e, "Error",
						JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	public boolean showDiscount(int discountId) {
		boolean success = true;
		Discount discount = null;
		try {
			if (discountId != 0) {
				discount = discountCtr.getDiscount(discountId);
			}
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}

		if (success) {
			textField_discountId.setText(Integer.toString(discount.getDiscountId()));
			textField_discountPercent.setText(Double.toString(discount.getDiscountPercentage()));
			textField_minPrice.setText(Integer.toString(discount.getMinPriceRequired()));
			isTextFieldEditable(false);
		}
		return success;
	}

	public void isTextFieldEditable(boolean isEditable) {
		textField_discountPercent.setEditable(isEditable);
		textField_minPrice.setEditable(isEditable);
		
	}

	public int getTextFieldId(JTextField textField) {
		int id = 0;
		try {
			id = Integer.parseInt(textField.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(null, "Please input number", "Error",
					JOptionPane.ERROR_MESSAGE);
		} finally {
			textField.setText("");
		}
		return id;
	}

	public void setBtnStartStatue() {
		btnCreate.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnSave.setEnabled(false);
	}

	public void setBtnEditStatue() {
		btnCreate.setEnabled(false);
		btnEdit.setEnabled(true);
		btnDelete.setEnabled(true);
		btnSave.setEnabled(true);
	}

	public void cleanTextField() {
		textField_searchId.setText("");
		textField_discountPercent.setText("");
		textField_minPrice.setText("");
		textField_discountId.setText("");
	}

	


}
